﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web;
using FaceSharp.MVC.Code.Data;
using FaceSharp.MVC.Code.Extensions;

namespace FaceSharp.MVC.Code.Repositories
{
    public class UserRepository
    {
        private readonly ShareThriftDataContext _dc;

        public UserRepository()
        {
            _dc = new ShareThriftDataContext();
        }

        private AppUser GetAppUser(long userId)
        {
            var user = (from u in _dc.AppUsers where u.Id == userId select u).FirstOrDefault();
            return user;
        }

        public void Install(long userId)
        {
            Trace.Write("Begin", "UserRepository.Install");
            var user = GetAppUser(userId);

            if (user == null)
            {
                user = new AppUser()
                {
                    Id = userId,
                    DateAdded = DateTime.UtcNow,
                    IsInstalled = true
                };
                _dc.AppUsers.InsertOnSubmit(user);
                _dc.SubmitChanges();
                Trace.Write("User Created", "UserRepository.Install");
            }
            else
            {
                Trace.Write("User Exists", "UserRepository.Install");
            }
            Trace.Write("End", "UserRepository.Install");
        }

        public void UnInstall(long userId)
        {
            Trace.Write("Begin", "UserRepository.UnInstall");
            var user = GetAppUser(userId);
            if(user != null)
            {
                user.IsInstalled = false;
                _dc.SubmitChanges();
                Trace.Write("User Removed", "UserRepository.UnInstall");
            }
            Trace.Write("End", "UserRepository.UnInstall");
        }
    }
}